package com.dooioo.pns.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dooioo.pns.api.leancloud.LeanCloudRequestUtils;
import com.dooioo.pns.business.service.AppInfoService;
import com.dooioo.pns.business.service.DeviceInfoService;
import com.dooioo.pns.business.service.DeviceLogoutTaskService;
import com.dooioo.pns.entity.enums.Platform;
import com.dooioo.pns.entity.model.DeviceInfo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * PackageName:com.dooioo.support.controller.api
 * Author: Jerry.hu
 * Create: Jerry.hu (2015-04-07 上午10:38)
 * Description:设备注册
 */
@Controller
@RequestMapping(value = "/api/device")
public class DeviceController extends BaseController{
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private AppInfoService appInfoService;
	@Autowired
	private LeanCloudRequestUtils leanCloudRequestUtils;
	@Autowired
	private DeviceLogoutTaskService deviceLogoutTaskService;
	/**
	 * 注册设备信息
	 * @param json json 体注入
	 * @return
	 */
	@RequestMapping(value = "/register",method = RequestMethod.POST)
	protected @ResponseBody
	ResponseEntity<?> register(@RequestBody String json
	) throws InterruptedException {
		Map<String,Object>  mp = new HashMap<>();
		JSONObject jsonObject;
		DeviceInfo deviceInfo = new DeviceInfo();
		try {
			jsonObject = JSON.parseObject(json);
		}catch (Exception e){
			mp.put("code", "400");
			mp.put("message","消息体格式不正确");
			return new ResponseEntity<>(mp, HttpStatus.BAD_REQUEST);
		}
		deviceInfo.setAppId(jsonObject.getIntValue("appId"));
		deviceInfo.setUuid(jsonObject.getString("uuid"));
		deviceInfo.setUserCode(jsonObject.getIntValue("userCode"));
		Assert.isTrue(deviceInfo.getUserCode() != 0, "userCode 值不正确");
		Assert.notNull(deviceInfo.getUuid(), "uuId 值不许为空");
		Assert.isTrue(deviceInfo.getAppId() != 0,"appId 值不正确");
		try {
			deviceInfo.setPlatform(Platform.valueOf(jsonObject.getString("platform")));
		}catch (Exception e){
			mp.put("code", "400");
			mp.put("message","platform 值不正确");
			return new ResponseEntity<>(mp, HttpStatus.BAD_REQUEST);
		}
		DeviceInfo oldDeviceInfo = deviceInfoService.getActiveDevice(deviceInfo);
		if(oldDeviceInfo != null){
			if(oldDeviceInfo.getStatus() == 1){
				if(!deviceInfo.getUuid().equals(oldDeviceInfo.getUuid()) || !deviceInfo.getPlatform().equals(oldDeviceInfo.getPlatform())) {
					DateTime dateTime = new DateTime();
					String s1 = dateTime.toString("HH:mm");
					String logoutMsg = "您的帐号" + deviceInfo.getUserCode()+"于"+s1+"在"+deviceInfo.getPlatform().toString()+"设备上登录。若非本人操作，您的密码可能已泄露，请及时在后台修改密码。";
					deviceLogoutTaskService.insert(oldDeviceInfo.getId(),logoutMsg);
					deviceInfo.setId(oldDeviceInfo.getId());
					deviceInfoService.updateBean(deviceInfo);
				}else{
					deviceInfo.setId(oldDeviceInfo.getId());
					deviceInfoService.updateBean(deviceInfo);
				}
			}else {
				deviceInfo.setId(oldDeviceInfo.getId());
				deviceInfoService.updateBean(deviceInfo);
			}
		}
		if(deviceInfo.getId() == 0){
			int deviceId = deviceInfoService.insertBean(deviceInfo);
			deviceInfo.setId(deviceId);
		}
		if (deviceInfo.getId() > 0) {
			leanCloudRequestUtils.register(deviceInfo, appInfoService.getHeaderMap(deviceInfo.getAppId()), false);
			mp.put("deviceId", deviceInfo.getId());
			return ResponseEntity.ok(mp);
		} else {
			mp.put("message", "操作异常,注册失败");
			return new ResponseEntity<>(mp, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}


	/**
	 * 注销设备信息
	 * @return ResponseEntity
	 */
	@RequestMapping(value = "/logout/{deviceId}",method = RequestMethod.DELETE)
	protected @ResponseBody
	ResponseEntity<?> logout(@PathVariable int deviceId){
		Map<String,String>  mp = new HashMap<>();
		DeviceInfo deviceInfo = deviceInfoService.getActiveDevice(deviceId);
		if(deviceInfo == null || deviceInfo.getStatus() > 1){
			mp.put("code", "404");
			mp.put("message", "资源不存在");
			return new ResponseEntity<>(mp, HttpStatus.NOT_FOUND);
		}
		deviceInfoService.logout(deviceId,2);
		leanCloudRequestUtils.logoff(deviceInfo, appInfoService.getHeaderMap(deviceInfo.getAppId()),false);
		mp.put("message","注销成功");
		mp.put("code","0");
		return ResponseEntity.ok(mp);
	}
}
